package com.example.eamh2system.netty.code;

import com.example.eamh2system.netty.message.ModbusResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class ModbusDecoder extends ByteToMessageDecoder {
    private static final int RESPONSE_HEADER_LENGTH = 2; // 响应头长度（功能码 + 字节数）

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
//        // 解析字节流为 Modbus 响应消息
//        int unitId = in.readUnsignedByte();
//        int functionCode = in.readUnsignedByte();
//        int byteCount = in.readUnsignedByte();
//
//        int[] data = new int[byteCount / 2];
//        for (int i = 0; i < data.length; i++) {
//            data[i] = in.readUnsignedShort();
//        }
//
//        ModbusResponse response = new ModbusResponse();
//        response.setUnitId(unitId);
//        response.setFunctionCode(functionCode);
//        response.setData(data);

            if (in.readableBytes() < RESPONSE_HEADER_LENGTH) {
                return; // 等待更多数据
            }

            in.markReaderIndex(); // 标记当前读索引位置

            // 读取功能码
            byte functionCode = in.readByte();
            if (functionCode != 0x01) {
                in.resetReaderIndex(); // 重置读索引位置
                return; // 不是预期的功能码，忽略该消息
            }

            // 读取字节数
            byte byteCount = in.readByte();

            // 读取线圈状态数据
            boolean[] coilStatus = new boolean[byteCount * 8];
            for (int i = 0; i < byteCount; i++) {
                byte b = in.readByte();
                for (int bit = 0; bit < 8; bit++) {
                    coilStatus[i * 8 + bit] = ((b & (1 << bit)) != 0);
                }
            }

            // 构造 Modbus 响应对象
            ModbusResponse response = new ModbusResponse();
            response.setCoilStatus(coilStatus);

            out.add(response); // 将解析得到的响应对象传递给下一个处理器
        }
}

